package cn.itsource.basic.service.impl;

import cn.itsource.basic.basicmapper.BasicMapper;
import cn.itsource.basic.domain.BaseDomain;
import cn.itsource.basic.query.BaseQuery;
import cn.itsource.basic.service.IBaseService;
import cn.itsource.basic.util.PageList;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

public class BaseServiceImpl<T extends BaseDomain,Q extends BaseQuery> implements IBaseService<T,Q> {

    @Autowired
    private BasicMapper<T> basicMapper;

    @Override
    public PageList<T> findPage(Q query) {

        //1.分页插件的使用
        PageHelper.startPage(query.getPage(),query.getSize());

        //2.执行分页语句 1，2顺序不能反  ，中间不能写代码
        //如果你要模块有高级查询怎么办？覆写
        List<T> ts = basicMapper.selectAll();

        //3.封装到pageInfo里面去
        PageInfo<T> pageInfo = new PageInfo<>(ts);

        //4.封装自定义pageList对象
        PageList<T> pageList = new PageList<>(pageInfo.getTotal(), pageInfo.getList());

        return pageList;
    }

    @Override
    public T findOne(Long id) {
        return basicMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<T> findAll() {
        return basicMapper.selectAll();
    }

    @Override
    @Transactional
    public void save(T t) {
        basicMapper.insertSelective(t);
    }

    @Override
    @Transactional
    public void update(T t) {

        //只有设置了值的字段才会被修改
        basicMapper.updateByPrimaryKeySelective(t);
    }

    @Override
    public void delete(Long id) {
        //删除一个对象
        basicMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void batchRemove(Q query) {
        if (query.getIds() == null || query.getIds().length == 0){
            return;
        }
        basicMapper.batchRemove(query.getIds());
    }

}
